<?php
/*
 * 命令行模式: 用以执行一些脚本
 */
class Controller_Cmd extends Controller 
{
	public function __construct(Request $req, Response $res)
	{
		if (! Kohana::$is_cli)
			throw new HTTP_Exception_404('File Not Found');

		parent::__construct($req, $res);
	}

	public function action_index ()
	{
		$this->help();
	}

    // 自动关闭团购活动
    public function action_autoCloseTuan ($timeout = 3600)
    {
        App_Tuan::autoClose($timeout);
    }

	public function action_reload_acl ()
	{
		$acl = Acl_Mgr::reload();
		if ($acl instanceof Acl)
			$this->response->body($this->color('green', 'Reload Acl Rules Successfully!') . "\n");
		else
			$this->response->body($this->color('red', 'sorrty, reload failed') . "\n");
	}

	private function help()
	{
		echo <<<EOF
this is command line mode for echome shangcheng

SYNOPSIS:

 php \$ROOT_DOCUMENT/index.php  [options]

OPTIONS:

 --uri=String
	request uri

 --method=String 
	request method	IN ('GET', 'POST')

 --get=String
	\$_GET params

 --post=String
	\$_POST params

 --referer=String 
	http referer 
\n
EOF;
	}

	private function color ($color, $str)
	{
		$color_indexs = array(
			'black' => 30,
			'red'   => 31,
			'green' => 32,
			'yellow' => 33,
			'blue'   => 34,
			'magenta' => 35,
			'cyan'    => 36,
			'gray'    => 37,
		);

		$color_index = isset($color_indexs[$color]) ? $color_indexs[$color] : 31;
		return sprintf("\033[%dm%s\033[0m", $color_index, $str); 
	}

    public function action_close_expire(){
        $data = $this->get_expire_activity();
        $this->close_expire_data($data,'mod_activity');
        $data = $this->get_expire_track();
        $this->close_expire_data($data,'mod_track');
    }

    public function get_expire_activity(){
        $today = date('Y-m-d');
        $query = DB::select('id')
            ->from('mod_activity')
            ->where('stopDay','<',$today)
            ->execute()
            ->as_array();

        return $query;
    }

    public function get_expire_track(){
        $today = date('Y-m-d');
        $query = DB::select('id')
            ->from('mod_track')
            ->where('stopDay','<',$today)
            ->execute()
            ->as_array();

        return $query;
    }

    public function close_expire_data($data,$table){
        $update = array('status'=>'INVALID');
        foreach($data as $v){
            $row = DB::update($table)
            ->set($update)
            ->where('id','=',$v['id'])
            ->execute();
            if($row > 0){
                kohana::$log->add(Log::DEBUG,'关闭---'.$table.':id----'.$v['id']);
            }
        }
    }
}
